package cn.akwangl.database;

import cn.akwangl.database.model.Person;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * JDBC简易封装
 *
 * @author youyongkun
 * @date 2021/5/23 4:27 下午
 */
public class DbUtils {

    private static DataSource dataSource;

    static {
        dataSource = new DataSource();
        dataSource.setUrl("jdbc:mysql://81.69.39.3:3306/bigdata?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8");
        dataSource.setUserName("root");
        dataSource.setPassword("123456");
    }

    private static Connection connection;
    private static PreparedStatement ps;
    private static ResultSet rs;

    private static Connection getConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(dataSource.getUrl(), dataSource.getUserName(), dataSource.getPassword());
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static List<Person> getPersonList(Integer size) {
        List<Person> result = new ArrayList();
        String sql = "SELECT * FROM bigdata.person LIMIT ?";
        try {
            DbUtils.getConnection();
            ps = connection.prepareStatement(sql);
            ps.setInt(1, size);
            rs = ps.executeQuery();
            while (rs.next()) {
                Person person = new Person();
                person.setId(rs.getString("id"));
                person.setName(rs.getString("name"));
                person.setSex(rs.getString("sex"));
                person.setAge(rs.getInt("age"));
                person.setEmail(rs.getString("email"));
                person.setTel(rs.getString("tel"));
                person.setAddress(rs.getString("address"));

                result.add(person);
            }
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
